package com.jiepos.mpos.biz.appInfM.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.biz.affix.service.AppAffixInfService;
import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppShareInfDao;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.App_Share_InfEntity;
import com.jiepos.mpos.common.entity.GpsEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 分享Service
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.biz.appInfM.service
 * @ClassName ShareService
 * @history
 * @UpdateRemark []
 * @since 2017/10/25
 */
@Service
public class ShareService extends BaseService {

    @Autowired
    private AppShareInfDao appShareInfDao;
    @Autowired
    private AppAffixInfService appAffixInfService;

    /**
     * 查询通知公告信息列表json分页数据
     *
     * @param pagination
     * @param appShareInfEntity
     * @return
     */
    public Map getShareList(HttpServletRequest request, Pagination pagination, App_Share_InfEntity appShareInfEntity, App_Ins_InfEntity appInsInfEntity) {
        StringBuffer sqlBuf = getInitSql("t1").append(",");
          sqlBuf.append("  t1.share_uuid as uuid, ")
                .append(" T2.INS_CD || '-' || T2.INS_CN_NM AS INST_NAME, ")
                .append("  t1.share_tp ||'-' || t4.code_desc  as share_tp, ")
                .append(" t1.share_title, t1.share_source,t1.source_url,t1.share_desc,t1.share_content, ")
                .append(" to_char(t1.publish_ts, 'yyyy-mm-dd hh24:mi:ss') as publish_ts, ")
                .append("  T1.PUBLISH_ST||'-' || T3.CODE_DESC as PUBLISH_ST  ")
                .append("   FROM "+ DBConstant.Table.T_APP_SHARE_INF+" t1 ")
                .append("   left join "+ DBConstant.Table.T_APP_INS_INF+" t2 ")
                .append("     on t1.ins_uuid = t2.ins_uuid ")
                .append("      LEFT JOIN "+ DBConstant.Table.T_APP_CODE_LIST+" T3  ON T1.PUBLISH_ST = t3.code_val and t3.code_tp='PUBLISH_ST' left join "+ DBConstant.Table.T_APP_CODE_LIST+" t4  on t1.share_tp =t4.code_val and t4.code_tp  = 'SHARE_TP'   where 1 = 1 ");
        List list = new ArrayList();

        //分享类型
        if (!StringUtils.isBlank(appShareInfEntity.getShare_tp())) {
            sqlBuf.append(" AND T1.Share_tp like ? ");
            list.add("%" + appShareInfEntity.getShare_tp() + "%");
        }
        //标题
        if (!StringUtils.isBlank(appShareInfEntity.getShare_title())) {
            sqlBuf.append(" AND T1.Share_title LIKE ? ");
            list.add("%" + appShareInfEntity.getShare_title() + "%");
        }
        //发布状态
        if (!StringUtils.isBlank(appShareInfEntity.getPublish_st())) {
            sqlBuf.append(" AND T1.PUBLISH_ST LIKE ? ");
            list.add("%" + appShareInfEntity.getPublish_st() + "%");
        }
        //机构名称
        if (!StringUtils.isBlank(appInsInfEntity.getIns_cn_nm())) {
            sqlBuf.append(" AND T2.ins_cn_nm LIKE ? ");
            list.add("%" + appInsInfEntity.getIns_cn_nm() + "%");
        }
        //机构号
        if (!StringUtils.isBlank(appInsInfEntity.getIns_cd())) {
            sqlBuf.append(" AND T2.ins_code LIKE ? ");
            list.add("%" + appInsInfEntity.getIns_cd() + "%");
        }

        pagination.queryString = sqlBuf.toString();
        pagination = getInsAuthSql(request, pagination, "T1", null);
        pagination = this.getOrderSql(pagination, "T1");
        return appShareInfDao.getPaginationMap(pagination, "T1", list);

    }

    /**
     * 根据记录id查询实体对象
     *
     * @param share_uuid
     * @return
     */
    public Map getShareById(String share_uuid) {
        if (StringUtils.isBlank(share_uuid) || share_uuid.equals("undefined")) {
            return new HashMap();
        }
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT  ")
                .append(" t1.share_uuid, ")
                .append(" T2.INS_CD || '-' || T2.INS_CN_NM AS INST_NAME, ")
                .append(" T1.ins_uuid, ")
                .append(" t1.share_tp, ")
                .append(" t1.share_title, t1.share_source,t1.source_url,t1.share_desc,t1.share_content,t1.rec_id,")
                .append(" to_char(t1.publish_ts, 'yyyy-mm-dd hh24:mi:ss') as publish_ts, ")
                .append("  T1.PUBLISH_ST  ")
                .append("   FROM "+ DBConstant.Table.T_APP_SHARE_INF+" t1 ")
                .append("   left join "+ DBConstant.Table.T_APP_INS_INF+" t2 ")
                .append("     on t1.ins_uuid = t2.ins_uuid ")
                .append("      LEFT JOIN "+ DBConstant.Table.T_APP_CODE_LIST+" T3  ON T1.PUBLISH_ST = t3.code_val and t3.code_tp='PUBLISH_ST' ")
                .append(" where t1.share_uuid = ? ");
        List<String> list = new ArrayList<>();
        list.add(share_uuid);
        List<Map<String, Object>> results = appShareInfDao.queryForList(getOrderSql(sqlBuf.toString(), "t1"), list);
        return results != null ? results.get(0) : new HashMap<String, Object>();
    }

    /**
     * 更新发布状态
     * @param share_uuids
     * @param publish_st
     * @param loginUser
     */
    public void updShareDetail(String share_uuids, String publish_st, Map loginUser) {
        appShareInfDao.updateByIds("share_uuid", share_uuids, publish_st,
                String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
    }

    /**
     * 保存
     * @param appShareInfEntity
     * @param map
     */
    public void saveShare(HttpServletRequest request,App_Share_InfEntity appShareInfEntity,String publish_date, Map map) {
        //当前用户
        appShareInfEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
        if (org.apache.commons.lang.StringUtils.isBlank(appShareInfEntity.getIns_uuid())) {
            appShareInfEntity.setIns_uuid(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_INS_UUID)));
        }
        if (!StringUtils.isBlank(appShareInfEntity.getShare_uuid())){
            //修改
            appShareInfEntity = (App_Share_InfEntity) this.saveCommonData(appShareInfEntity, map, "update");
            appShareInfEntity.setPublish_ts(new Timestamp(DateUtil.strToDate(publish_date, DateUtil.FORMAT_TIME).getTime()));
            List noChangeList = new ArrayList();
            noChangeList.add("share_uuid");
            noChangeList.add("rec_crt_ts");
            appShareInfDao.update(appShareInfEntity, noChangeList);
            appAffixInfService.saveAffixPic(request,appShareInfEntity.getShare_uuid(),map);
        } else {
            //新增
            appShareInfEntity.setShare_uuid(IDFactoryUtil.getUUID());
            appShareInfEntity.setPublish_st(SystemConstant.PUBLISH_ST);// 已发布状态

            appShareInfEntity.setPublish_ts(new Timestamp(DateUtil.strToDate(publish_date, DateUtil.FORMAT_TIME).getTime()));
            appShareInfEntity = (App_Share_InfEntity) this.saveCommonData(appShareInfEntity, map, "null");
            appShareInfDao.save(appShareInfEntity);
            appAffixInfService.saveAffixPic(request,appShareInfEntity.getShare_uuid(),map);
        }
    }

    /**
     /**
     * 根据分享类型获取分享信息列表
     */
    public List getShareByTp(String ins_uuid, String share_tp,String curr_page,String rows_perpage,GpsEntity gpsEntity) {
        Pagination pagination = new  Pagination();
        pagination.setPage(Integer.parseInt(curr_page));
        pagination.setRows(Integer.parseInt(rows_perpage));
        String appType = gpsEntity.getAppType();
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT t1.share_uuid as \"share_uuid\", ")
                .append(" t1.share_tp || NVL2(t4.code_desc, '-'||t4.code_desc, '') AS \"share_tp\", ")
                .append(" t1.share_title as \"share_title\", t1.share_source ||'-' || t3.code_desc as \"share_source\",")
                .append(" to_char(t1.publish_ts, 'yyyy-mm-dd hh24:mi:ss') as \"publish_ts\", ")
                .append(" t1.source_url as \"source_url\",t1.share_desc as \"share_desc\" ")
                .append("   FROM "+ DBConstant.Table.T_APP_SHARE_INF+" t1 ")
                .append("   left join "+ DBConstant.Table.T_APP_INS_APP+" t2 ")
                .append("     on t1.ins_uuid = t2.ins_uuid ")
                .append("      LEFT JOIN "+ DBConstant.Table.T_APP_CODE_LIST+" T3  ON T1.Share_Source = t3.code_val and t3.code_tp='SHARE_SOURCE' ")
                .append(" left join "+ DBConstant.Table.T_APP_CODE_LIST+" t4  on t1.share_tp = t4.code_val and t4.code_tp  = 'SHARE_TP'  ")
                .append(" where 1 = 1 and publish_st = "+SystemConstant.PUBLISH_ST+"  and t1.rec_st="+ SystemConstant.REC_ST_1+" and t1.share_tp = ? and t1.ins_uuid = ? ");
        if (SystemConstant.APP_TYPE_IOS.equals(appType)) {
            sqlBuf.append(" and t2.ios_appid=?");
        } else {
            sqlBuf.append(" and t2.android_appid=?");
        }
        
        List<String> list = new ArrayList<>();
        list.add(share_tp);
        list.add(ins_uuid);
        list.add(gpsEntity.getApp_id());
        List<Map<String, Object>>  results = new ArrayList<Map<String, Object>>();
        if("1".equals(share_tp)){
             results = appShareInfDao.queryForList(getOrderSql(sqlBuf.toString(), "t1"), list);
        }else{
            pagination.queryString = sqlBuf.toString();
            pagination = appShareInfDao.getPagination(pagination, "t1", list);
            results =  pagination.getOldData();
        }

        Map shareMap = new HashMap();
        if(results != null && results.size()>0 ){
            shareMap  = results.get(0);

            List picList = null;
            Map picMap = null;
            for(int i = 0 ; i < results.size() ; i++){
            	Map map = results.get(i);
                String share_uuid = String.valueOf(map.get("share_uuid"));
                picList = appAffixInfService.getAffixPic(SystemConstant.AFFIX_TP_06, share_uuid);

                for(int j = 0 ; j < picList.size() ; j++){
                    picMap = (Map)picList.get(j);
                    String store_tp = String.valueOf(picMap.get("store_tp"));
                    String affix_path = String.valueOf(picMap.get("affix_path"));
                    //IOS缩略图
                    if(SystemConstant.APP_TYPE_IOS.equals(appType) && SystemConstant.AFFIX_TP_06_03.equals(store_tp) ){
                        map.put("ios_thumb_2xpic", affix_path);
                        map.put("ios_thumb_3xpic", "");
                    }
                    //IOS引导图
                    if(SystemConstant.APP_TYPE_IOS.equals(appType) && SystemConstant.AFFIX_TP_06_04.equals(store_tp) ){
                        map.put("ios_intro_2xpic", affix_path);
                        map.put("ios_intro_3xpic", "");
                    }
                    //安卓缩略图
                    if(SystemConstant.APP_TYPE_ANDROID.equals(appType) && SystemConstant.AFFIX_TP_06_01.equals(store_tp)){
                        map.put("android_thumb_pic", affix_path);
                    }
                    //安卓引导图
                    if(SystemConstant.APP_TYPE_ANDROID.equals(appType) && SystemConstant.AFFIX_TP_06_02.equals(store_tp)){
                        map.put("android_intro_pic", affix_path);
                    }
                }

            }
        }
        return results;
    }


    /**
     /**
     * 根据分享类型获取分享信息详情
     */
    public Map getShareDetailById(String ins_uuid, String share_uuid, GpsEntity gpsEntity) {
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" select  t1.share_uuid as \"share_uuid\",")
                .append("  t1.share_tp ||'-' || t4.code_desc as \"share_tp\", ")
                .append(" t1.share_title as \"share_title\", t1.source_url \"source_url\",t1.share_desc as \"share_desc\",t1.share_content as \"share_content\", ")
                .append(" to_char(t1.publish_ts, 'yyyy-mm-dd hh24:mi:ss') as \"publish_ts\", ")
                .append(" t1.share_source ||'-' || t3.code_desc as \"share_source\"")
                .append("   FROM "+ DBConstant.Table.T_APP_SHARE_INF+" t1 ")
                .append("   left join "+ DBConstant.Table.T_APP_INS_INF+" t2 ")
                .append("     on t1.ins_uuid = t2.ins_uuid ")
                .append("      LEFT JOIN "+ DBConstant.Table.T_APP_CODE_LIST+" T3  ON T1.share_source = t3.code_val and t3.code_tp='SHARE_SOURCE' left join "+ DBConstant.Table.T_APP_CODE_LIST+" t4  on t1.share_tp =t4.code_val and t4.code_tp  = 'SHARE_TP' where 1 = 1 ")
                .append(" and t1.rec_st="+ SystemConstant.REC_ST_1+" and  t1.ins_uuid = ? and t1.share_uuid = ?");
        List list = new ArrayList();
        list.add(ins_uuid);
        list.add(share_uuid);
        List<Map> results = appShareInfDao.queryForList(getOrderSql(sqlBuf.toString(), "t1"), list);
        if(CollectionUtil.isEmpty(results)){
            return null;
        }
        return results.get(0);
    }
}
